﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DotNetNuke.Web.Services;
using System.Web.Mvc;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Security.Roles;
using DotNetNuke.Modules.ActiveSocialMigrator.Data;
using Active.Modules.Social;
using DotNetNuke.Security.Roles.Internal;
using DotNetNuke.Services.FileSystem;
using System.IO;
using System.Data;
using DotNetNuke.Services.Journal;
using DotNetNuke.Modules.ActiveSocialMigrator.Utilities;

namespace DotNetNuke.Modules.ActiveSocialMigrator.Services
{
    [DnnAuthorize]
    public class ProfilesServiceController : DnnController
    {
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateAntiForgeryToken]
        public ActionResult MoveProfilePics()
        {
            IFileManager _fileManager = FileManager.Instance;
            IFolderManager _folderManager = FolderManager.Instance;
            var rootFolderPath = PathUtils.Instance.FormatFolderPath(PortalSettings.HomeDirectory + "/activesocial/profiles/_icons");
            if (!System.IO.File.Exists(rootFolderPath))
            {
                return Json(new { Result = "No profile pictures found." });
            }
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(PathUtils.Instance.MapPath(rootFolderPath));
           

            foreach (System.IO.FileInfo f in di.GetFiles("pp_*.png")) {
                try
                {
                    string fileName = f.Name.Replace("pp_", "").Replace(".png", "");
                    if (!fileName.Contains("_"))
                    {
                        int UserId = Convert.ToInt32(fileName);
                        DotNetNuke.Entities.Users.UserInfo ui = DotNetNuke.Entities.Users.UserController.GetUser(PortalSettings.PortalId, UserId, true);
                        var userFolder = _folderManager.GetUserFolder(ui);
                        var file = System.IO.File.Open(f.FullName, FileMode.Open);
                        var fileInfo = _fileManager.AddFile(userFolder, f.Name, file, true);
                        file.Close();
                        file.Dispose();

                        ui.Profile.Photo = fileInfo.FileId.ToString();
                        DotNetNuke.Entities.Users.UserController.UpdateUser(PortalSettings.PortalId, ui);
                    }
                }
                catch
                {
                }
                
                
            }
            return Json(new { Result = "success" });
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateAntiForgeryToken]
        public ActionResult MoveFriends() {
            var friendsDB = new FriendsDB();
            friendsDB.MoveFriends();
            return Json(new { Result = "success" });
        }
    }
}